package com.cms.material

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.util.TypedValue
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ItemDecoration
import com.android.baselibrary.base.BaseAdapter

class NbdStickItemDivider : ItemDecoration {

    private var mLinePaint: Paint
    private var mTextPaint: Paint
    private var mItemHeaderPaint: Paint
    private var mTextRect: Rect
    private var mTextPaddingLeft: Int
    private var mItemHeaderHeight: Int
    private var mIsTextCenter = false


    constructor(
            context: Context, height: Float = 40f,
            /**
             * 背景色
             */
            bgColor: Int = 0,
            /**
             * 文字颜色
             */
            textColor: Int = 0,
            /**
             * 文字大小
             */
            textSize: Float = 14f,
            /**
             * 文字距离左边的距离
             */
            textPaddingLeft: Float = 0f,
            /**
             * 文字是否居中
             */
            isTextCenter: Boolean = false,
            lineColor: Int = Color.parseColor("#cccccc"),
    ) {

        mIsTextCenter = isTextCenter

        mItemHeaderHeight = dp2px(context, height)
        mTextPaddingLeft = dp2px(context, textPaddingLeft)

        mTextRect = Rect()

        mItemHeaderPaint = Paint(Paint.ANTI_ALIAS_FLAG)
        // 设置背景颜色
        if (bgColor != 0) {
            mItemHeaderPaint.color = bgColor
        }
        mTextPaint = Paint(Paint.ANTI_ALIAS_FLAG)

        mTextPaint.textSize = sp2px(context, textSize)

        // 设置字体颜色
        if (textColor == 0) {
            mTextPaint.color = Color.WHITE
        } else {
            mTextPaint.color = textColor
        }

        // 分割线的颜色
        mLinePaint = Paint(Paint.ANTI_ALIAS_FLAG)
        mLinePaint.color = lineColor
    }

    /**
     * 绘制Item的分割线和组头
     */
    override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        val adapter = parent.adapter
        if (adapter is BaseAdapter<*,*>) {
            // 获取可见范围内Item的总数
            val count = parent.childCount
            for (i in 0 until count) {
                val view = parent.getChildAt(i)
                val position = parent.getChildLayoutPosition(view)
                val isHeader = adapter.isItemStick(position)
                val left = parent.paddingLeft.toFloat()
                val right = parent.width - parent.paddingRight.toFloat()
                if (isHeader) {
                    c.drawRect(
                            left,
                            (view.top - mItemHeaderHeight).toFloat(),
                            right,
                            view.top.toFloat(),
                            mItemHeaderPaint
                    )

                    mTextPaint.getTextBounds(
                            adapter.getGroupName(position),
                            0,
                            adapter.getGroupName(position).length,
                            mTextRect
                    )
                    // 居中
                    var tempX = left + mTextPaddingLeft

                    if (mIsTextCenter) {
                        tempX = right / 2 - mTextRect.width() / 2
                    }

                    c.drawText(
                            adapter.getGroupName(position),
                            tempX,
                            ((view.top - mItemHeaderHeight) + mItemHeaderHeight / 2 + mTextRect.height() / 2).toFloat(),
                            mTextPaint
                    )

                } else {
                    // 组尾加分割线
                    if (adapter.getDataList().size - 2 > position && adapter.isItemStick(position + 1)) {
                        c.drawRect(
                                left, (view.bottom - dp2px(parent.context, 0.5f)).toFloat(), right, view.bottom.toFloat(), mLinePaint
                        )
                    }
                }
            }
        }
    }

    /**
     * Item 吸顶效果
     */
    override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        val adapter = parent.adapter
        if (adapter is BaseAdapter<*,*>) {
            val position =
                    (parent.layoutManager as LinearLayoutManager).findFirstVisibleItemPosition()
            val view = parent.findViewHolderForAdapterPosition(position)?.itemView ?: return
            val isHeader = adapter.isItemStick(position + 1)
            val top = parent.paddingTop.toFloat()
            val left = parent.paddingLeft.toFloat()
            val right = parent.width - parent.paddingRight.toFloat()


            // 居中
            var tempX = left + mTextPaddingLeft

            if (mIsTextCenter) {
                tempX = right / 2 - mTextRect.width() / 2
            }
            if (isHeader) {
                val bottom = mItemHeaderHeight.coerceAtMost(view!!.bottom)
                c.drawRect(
                        left, top + view.top - mItemHeaderHeight, right, top + bottom, mItemHeaderPaint
                )
                mTextPaint.getTextBounds(
                        adapter.getGroupName(position),
                        0,
                        adapter.getGroupName(position).length,
                        mTextRect
                )

                c.drawText(
                        adapter.getGroupName(position),
                        tempX,
                        top + mItemHeaderHeight / 2 + mTextRect.height() / 2 - (mItemHeaderHeight - bottom),
                        mTextPaint
                )
            } else {
                c.drawRect(left, top, right, top + mItemHeaderHeight, mItemHeaderPaint)
                mTextPaint.getTextBounds(
                        adapter.getGroupName(position),
                        0,
                        adapter.getGroupName(position).length,
                        mTextRect
                )
                c.drawText(
                        adapter.getGroupName(position),
                        tempX,
                        top + mItemHeaderHeight / 2 + mTextRect.height() / 2,
                        mTextPaint
                )
            }
            c.save()
        }
    }


    /**
     * 设置Item的间距
     */
    override fun getItemOffsets(
            outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State
    ) {
        val adapter = parent.adapter
        if (adapter is BaseAdapter<*,*>) {
            val position = parent.getChildLayoutPosition(view)
            val isHeader = adapter.isItemStick(position)
            if (isHeader) {
                outRect.top = mItemHeaderHeight
            } else {
                outRect.top = 1
            }
        }
    }

    private fun dp2px(context: Context, dpValue: Float): Int {
        val scale = context.resources.displayMetrics.density
        return (dpValue * scale + 0.5f).toInt()
    }

    private fun sp2px(context: Context, spValue: Float): Float {
        return TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_SP, spValue, context.resources.displayMetrics
        )
    }
}